package com.sample.springbatch.controller;

import com.sample.springbatch.thread.CreateJobInstanceThread;
import com.sample.springbatch.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.*;

/**
 * 测试接口
 *
 * @author zwg
 * @date 2023/11/28 16:22
 */
@Slf4j
@RestController
@RequestMapping(value = "test")
public class TestController {
    @Autowired
    JobRepository jobRepository;

    @Autowired
    JobLauncher launcher;

    @GetMapping(value = "/runJob/{jobName}")
    public String runJob(@PathVariable(name = "jobName") String jobName){
        Map<String, JobParameter> parameters = new HashMap();
        parameters.put("time", new JobParameter(System.currentTimeMillis()));
        Job job = SpringContextHolder.getBean(jobName);
        if(job==null){
            return "not find job "+jobName;
        }

        String result = "";
        try {
            JobExecution jobExecution = launcher.run(job, new JobParameters(parameters));
            result = "jobExecution:"+jobExecution.toString();
        }catch(Exception e){
            log.error("error:",e);
            result = "jobExecution fail:"+e.getMessage();
        }
        return result;

    }


    @GetMapping(value = "/jobInstance")
    public String testJobInstance(){
        String jobName = "test123";
        List<Future<String>> futureList = new ArrayList<>();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,10,10, TimeUnit.SECONDS,new ArrayBlockingQueue<>(5000));
        for(int i=0; i<5000; i++){
            Future<String> future = executor.submit(new CreateJobInstanceThread(jobRepository,jobName,"task-"+i));
            futureList.add(future);
        }
        Set<String> jobKeySet = new HashSet<>();
        int count = 0;
        for (Future future : futureList) {
            try {
                if(future.isDone()){
                    count++;
                    //log.info("thread [{}] is run done",future.get());

                }else{
                    Object taskId = future.get(10L, TimeUnit.SECONDS);
                    if(future.isDone()){
                        count++;
                    }
                    //log.info("thread [{}] is stop",taskId);
                }
                if(jobKeySet.contains(future.get())){
                    log.info("a=={}",future.get());
                }else{
                    jobKeySet.add(future.get().toString());
                }
                System.out.println(future.get());
            } catch (Exception e) {
                log.error("future error:",e);
            }
        }

        return "ok-"+count;
    }


}
